package com.qidian.blog.servlet;

import com.qidian.blog.util.Const;
import com.qidian.blog.util.JSONTools;
import com.qidian.blog.util.pojo.QDResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * 2022/9/22 15:03
 */
public class BaseServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName = req.getParameter("op");// add
        // 通过反射获取一个方法
        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 执行方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            respJson(QDResult.fal(Const.RESPONSE_STATUS_ERROR),resp);
        }
    }

    protected void respJson(Object obj,HttpServletResponse response) throws IOException {
        response.setContentType(Const.RES_JSON);
        response.getWriter().write(JSONTools.object2json(obj));
    }
}
